package com.hstx.demo.mqtt.controller;

import com.hstx.demo.mqtt.until.Log;
import javafx.scene.control.TextArea;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

public class MqttRecivePushCallBack implements MqttCallback {
    private TextArea txtareRecevieMsg;

    public MqttRecivePushCallBack(TextArea txtareRecevieMsg) {
        this.txtareRecevieMsg = txtareRecevieMsg;
    }

    @Override
    public void connectionLost(Throwable throwable) {
        // 连接丢失后，一般在这里面进行重连
        Log.error(getClass(), "连接断开，可以做重连");
        txtareRecevieMsg.appendText("连接断开，可以做重连" + "\n\n");
    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        // subscribe后得到的消息会执行到这里面
        Log.info(getClass(), "接收消息主题 : " + topic);
        txtareRecevieMsg.appendText("接收消息主题 : " + topic + "\n");
        Log.info(getClass(), "接收消息Qos : " + mqttMessage.getQos());
        txtareRecevieMsg.appendText("接收消息Qos : " + mqttMessage.getQos() + "\n");
        Log.info(getClass(), "接收消息内容 : " + new String(mqttMessage.getPayload()));
        txtareRecevieMsg.appendText("接收消息内容 : " + new String(mqttMessage.getPayload()) + "\n\n");
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        Log.info(getClass(), "发送完成 #=> " + iMqttDeliveryToken.isComplete());
        txtareRecevieMsg.appendText("发送完成 #=> " + iMqttDeliveryToken.isComplete() + "\n\n");
    }
}
